const WebSocket = require('ws')
const wss = new WebSocket.Server({ noServer: true })
const http = require('http')
const server = http.createServer()
const jwt = require('jsonwebtoken')

// let num = 0
let group = {}
const timeInterval = 1000 //创建时间
wss.on('connection', function connection(ws) {
  //给定默认否则会treme
  ws.isAlive = true
  console.log('一个连接')

  // ws.on('message', function (msg) {
  //   ws.send(msg)
  // })
  // ws.send('wellcom  ')
  //多聊天室
  ws.on('message', function (msg) {
    const msgobj = JSON.parse(msg)
    if (msgobj.event === 'enter') {
      ws.name = msgobj.message
      ws.room = msgobj.room
      if (typeof group[ws.room] === 'undefined') {
        group[ws.room] = 1
      } else {
        group[ws.room]++
      }
    }
    //鉴权
    if (msgobj.event === 'auth') {
      jwt.verify(msgobj.message, 'secret', (err, decode) => {
        if (err) {
          //鉴权失败
          ws.send(
            JSON.stringify({
              event: 'noauth',
              message: 'please auth again',
            })
          )
          console.log('auth error')
          return
        } else {
          console.log(decode)
          ws.isAuth = true
          return
        }
      })
      return
    }
    // 鉴权通过后
    if (!ws.isAuth) {
      return
    }
    //心跳检测
    if (msgobj.event === 'heartbeat' && msgobj.message === 'pong') {
      ws.isAlive = true
      return
    }
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN && client.room === ws.room) {
        msgobj.name = ws.name //返回名字
        // msgobj.num = wss.clients.size //在线人数
        // msgobj.num = num //在线人数
        msgobj.num = group[ws.room] //在线人数
        // client.send(msg)
        client.send(JSON.stringify(msgobj))
      }
    })
  })
  ws.on('close', function () {
    if (ws.name) {
      //num--//
      group[ws.room]--
    }

    let msgobj = {}
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN && ws.room === client.room) {
        msgobj.name = ws.name //返回名字
        // msgobj.num = wss.clients.size //在线人数
        // msgobj.num = num //在线人数
        msgobj.num = group[ws.room] //在线人数
        msgobj.event = 'out'
        // client.send(msg)
        client.send(JSON.stringify(msgobj))
      }
    })
  })
})

server.on('upgrade', function upgrade(request, socket, head) {
  console.log('requsert', request.headers)
  // This function is not defined on purpose. Implement it with your own logic.
  // authenticate(request, function next(err, client) {
  //   if (err || !client) {
  //     socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
  //     socket.destroy();
  //     return;
  //   }

  wss.handleUpgrade(request, socket, head, function done(ws) {
    wss.emit('connection', ws, request)
  })
  // });
})

setInterval(() => {
  wss.clients.forEach((ws) => {
    if (ws.isAlive === false && WSH.room) {
      group[ws.room]--
      deletews['room']
      return ws.terminate() //ws 终止websocke方法
    }
    //主动发送心跳请求
    // 客户端返回了消息，主动设置flag为在线
    ws.isAlive = false
    ws.send(
      JSON.stringify({
        event: 'heartbeat',
        message: 'ping',
        num: group[ws.room],
      })
    )
  })
}, timeInterval)

server.listen(3000)
